package com.healthcarex.hip.saas.message.service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;

import com.healthcarex.hip.saas.message.processor.IMessageProcessor;
import com.healthcarex.hip.saas.message.creator.IMessageCreator;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;


public class MessageService {
    private static final Logger logger = LoggerFactory
            .getLogger(MessageService.class);

    private static MessageService _instance;
    private Map<String, IMessageCreator> creatorList;
    private ServiceLoader<IMessageCreator> creatorLoader;
    private Map<String, IMessageProcessor> processorList;
    private ServiceLoader<IMessageProcessor> processorLoader;

    private MessageService() {
        init();
        register();
    }

    public static MessageService getInstance() {
        if (_instance == null) {
            _instance = new MessageService();
        }
        return _instance;
    }

    /**
     * @param type type
     */
    public IMessageCreator getCreator(String type) {
        return creatorList.get(type);
    }

    /**
     * @param type type
     */
    public IMessageProcessor getProcessor(String type) {
        return processorList.get(type);
    }

    /*public IMessageParser getParser(String type) {
        return parserList.get(type);
    }
*/
    private void init() {
        processorLoader = ServiceLoader.load(IMessageProcessor.class);
        processorList = new HashMap<String, IMessageProcessor>();

        creatorLoader = ServiceLoader.load(IMessageCreator.class);
        creatorList = new HashMap<String, IMessageCreator>();

    }

    private void register() {
        try {
            Iterator<IMessageProcessor> processorIt = processorLoader
                    .iterator();
            while (processorIt.hasNext()) {
                IMessageProcessor processor = processorIt.next();
                processorList.put(processor.getMessageType(), processor);
            }

            Iterator<IMessageCreator> creatorIt = creatorLoader.iterator();
            while (creatorIt.hasNext()) {
                IMessageCreator creator = creatorIt.next();
                creatorList.put(creator.getMessageType(), creator);
            }

        } catch (ServiceConfigurationError serviceError) {
            serviceError.printStackTrace();
            logger.error(serviceError.toString());
        }
    }

}